﻿using IdentityModel;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;

namespace Datav.Design.Jwt
{
    /// <summary>
    ///
    /// </summary>
    public class JwtTokenHelper
    {
        /// <summary>
        ///
        /// </summary>
        /// <param name="ticket"></param>
        /// <param name="signingCredentials"></param>
        /// <param name="key"></param>
        /// <param name="action"></param>
        /// <param name="expires">超时时间</param>
        /// <returns></returns>
        public static Zdap.Common.UserTicket BuildJwtToken(Zdap.Common.UserTicket ticket, SigningCredentials signingCredentials, string key, Action<string, string> action, DateTime expires)
        {
            var claims = new Claim[]
                {
                    new Claim(JwtClaimTypes.Id, ticket.Id.ToString()),
                    new Claim(JwtClaimTypes.Name, ticket.Name??string.Empty),
                    new Claim("timestamp", DateTime.Now.Ticks.ToString())
                };
            var jwt = new JwtSecurityToken(claims: claims, signingCredentials: signingCredentials, expires: expires);
            var token = new JwtSecurityTokenHandler().WriteToken(jwt);
            ticket.AccessToken = token;
            action(key, token);
            return ticket;
        }
    }
}